package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.config.LocationContext;
import cn.com.ejiakanghu.core.utils.LngLatUtil;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.dto.*;
import cn.com.ejiakanghu.task.CommonThreadPool;
import cn.com.ejiakanghu.vo.HospitalLinkDataVo;
import cn.hutool.core.util.ObjectUtil;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.util.IpUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.app.AppHomeMapper;
import org.linlinjava.litemall.db.dao.divided.LitemallCartPromoteMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.GlobalConstantData;
import org.linlinjava.litemall.db.util.GoodsConstant;
import org.linlinjava.litemall.db.vo.app.StoreGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;

/**
 * @author houzb
 * @Description
 * @create 2021-04-04 20:32
 */
@Component
public class HomeManager {

    @Autowired
    private LitemallAdService adService;

    @Autowired
    private LitemallGoodsService goodsService;

    @Autowired
    private LitemallBrandService brandService;

    @Autowired
    private LitemallTopicService topicService;

    @Autowired
    private LitemallCategoryService categoryService;

    @Autowired
    private WxGrouponRuleService grouponService;

    @Autowired
    private LitemallCouponService couponService;

    @Autowired
    private AgedmallAppNoticeService agedmallAppNoticeService;

    @Autowired
    private LitemallKeywordService keywordsService;

    @Autowired
    private AgedmallTopicDataService agedmallTopicDataService;

    @Autowired
    private LitemallTopicService litemallTopicService;
    @Autowired
    private AgedmallSalePointService agedmallSalePointService;
    @Autowired
    private AgedmallTopicImgService agedmallTopicImgService;
    @Autowired
    private LitemallRegionService litemallRegionService;
    @Autowired
    private GoodsManager goodsManager;
    @Resource
    private AgedmallHospitalSendMapper agedmallHospitalSendMapper;

    @Resource
    private AgedmallHospitalSendGoodsAttributeMapper agedmallHospitalSendGoodsAttributeMapper;

    @Resource
    private AgedmallHospitalSendRelationMapper agedmallHospitalSendRelationMapper;

    @Resource
    private AgedmallHospitalChannelLinkMapper agedmallHospitalChannelLinkMapper;

    @Resource
    private AgedmallAgentMapper agedmallAgentMapper;

    @Resource
    private AppHomeMapper appHomeMapper;

    @Resource
    private AgedmallPromoteCountMapper agedmallPromoteCountMapper;

    public BaseResult getHomeData(Integer saleUserId,Integer userId,HttpServletRequest request) {
        Location location = LocationContext.get();
        String city = location.getCity();
//        Integer cityId = litemallRegionService.getCityIdByName(city);
//        String redisKey = HomeCacheManager.INDEX + cityId;
//        //优先从缓存中读取
//        if (HomeCacheManager.hasData(redisKey)) {
//            return RespUtil.success(HomeCacheManager.getCacheData(redisKey));
//        }
//        ExecutorService executorService = CommonThreadPool.COMMON_THREAD_POOL;


        //轮播banner
        List<LitemallAd> adList = adService.queryByCity(city);
        // 通知
        List<AgedmallAppNotice> noticeList = agedmallAppNoticeService.querySelective(null, null, 1, 10, "id", "desc");
        List<AppNoticeInfo> noticeInfoList = new ArrayList<>();
        noticeList.stream().forEach(n -> {
            noticeInfoList.add(new AppNoticeInfo(n.getTitle()));
        });

        //取出热闹关键词
        List<LitemallKeyword> hotKeywordList = keywordsService.queryHots();
        List<AppKeywordInfo> hotKeyList = new ArrayList<>();
        hotKeywordList.stream().forEach(k -> {
            hotKeyList.add(new AppKeywordInfo(k.getKeyword()));
        });

        // 卖点
        List<AgedmallSalePoint> salePoints = agedmallSalePointService.list();
        List<AppSalePointInfo> salePointList = salePoints.stream().map(AppSalePointInfo::new).collect(Collectors.toList());

        // 推荐图片
        AgedmallTopicImg saleImg = agedmallTopicImgService.getByType(GoodsConstant.GOODS_TYPE_SALE);
        AgedmallTopicImg leaseImg = agedmallTopicImgService.getByType(GoodsConstant.GOODS_TYPE_LEASE);

        // 送货上门推荐数据
        List<AgedmallTopicData> saleTopicDatas = agedmallTopicDataService.getByType(GoodsConstant.GOODS_TYPE_SALE);
        List<Integer> saleGoodsIds = saleTopicDatas.stream().map(AgedmallTopicData::getStoreGoodsId).collect(Collectors.toList());
        List<StoreGoodsVo> saleRecommends = goodsManager.getNearestStoreGoodsList(saleGoodsIds, location.getLng(), location.getLat(), city,null);
        List<GoodsBaseData> hotsaleList = saleRecommends.stream().map(GoodsBaseData::getInstance).collect(Collectors.toList());

        List<AgedmallTopicData> leaseTopicDatas = agedmallTopicDataService.getByType(GoodsConstant.GOODS_TYPE_LEASE);
        List<Integer> leaseGoodsIds = leaseTopicDatas.stream().map(AgedmallTopicData::getStoreGoodsId).collect(Collectors.toList());
        List<StoreGoodsVo> leaseRecommends = goodsManager.getNearestStoreGoodsList(leaseGoodsIds, location.getLng(), location.getLat(), city,null);
        List<GoodsBaseData> hotleaseList = leaseRecommends.stream().map(GoodsBaseData::getInstance).collect(Collectors.toList());


        // 多个专题分类的商品列表
        List<LitemallTopic> litemallTopicList = litemallTopicService.list();
        List<AppSpecialInfo> appSpecialInfoList = litemallTopicList.stream().map(p ->{
            String[] goodsIds = p.getGoods().split(",");
            List<Integer> goodsIdList  = Arrays.stream(goodsIds).map(Integer::parseInt).collect(Collectors.toList());
            List<StoreGoodsVo> goods = goodsManager.getNearestStoreGoodsList(goodsIdList, location.getLng(), location.getLat(), city,null);
            List<GoodsBaseData> goodsList = goods.stream().map(GoodsBaseData::getInstance).collect(Collectors.toList());
            return new AppSpecialInfo(p, goodsList);
        }).collect(Collectors.toList());

        //推广员商品列表数据
        SaleUserRecommendDto saleUserRecommendDto=new SaleUserRecommendDto();
        if(saleUserId!=null){
            AgedmallAgent agedmallAgent=agedmallAgentMapper.selectByPrimaryKey(saleUserId);
            AgedmallCustomTemplate customAusleseMessage = appHomeMapper.getCustomAusleseMessage(agedmallAgent.getId());
            if(StringUtils.isNotBlank(customAusleseMessage.getCanCustomGoods())){
                String[] goodsIds = customAusleseMessage.getCanCustomGoods().split(",");
                List<Integer> goodsIdList  = Arrays.stream(goodsIds).map(Integer::parseInt).collect(Collectors.toList());
                List<StoreGoodsVo> goods = goodsManager.getNearestStoreGoodsList(goodsIdList, location.getLng(), location.getLat(), city,null);
                List<GoodsBaseData> goodsList = goods.stream().map(GoodsBaseData::getInstance).collect(Collectors.toList());
                saleUserRecommendDto.setGoodsList(goodsList);
                if(customAusleseMessage.getAusleseShow() != null && customAusleseMessage.getAusleseShow()==1){
                    saleUserRecommendDto.setTitle(customAusleseMessage.getAusleseBackgroundTitle());
                    saleUserRecommendDto.setNotes(customAusleseMessage.getAusleseBackgroundContent());
                    saleUserRecommendDto.setBgImg(customAusleseMessage.getAusleseBackgroundImage());
                }
            }
            this.insertPromoteInformation(saleUserId,userId,agedmallAgent);
        }

        Map<String, Object> entity = new HashMap<>();
        try {
            List<AppBannerInfo> bannerInfoList = new ArrayList<>();
            adList.stream().forEach(ad -> {
                AppBannerInfo bannerInfo = new AppBannerInfo();
                bannerInfo.setImage(ad.getUrl());
                bannerInfo.setUrl(ad.getLink());
                bannerInfo.setEvent(ad.getEventType());
                bannerInfoList.add(bannerInfo);
            });

            Map<String, List<GoodsBaseData>> homeRecommendMap = new HashMap<>();
            homeRecommendMap.put("hotsaleList", hotsaleList);
            homeRecommendMap.put("hotleaseList", hotleaseList);

            Map<String, String> recommendImgMap = new HashMap<>();
            recommendImgMap.put("saleImg", null == saleImg ? "" : saleImg.getUrl());
            recommendImgMap.put("leaseImg", null == leaseImg ? "" : leaseImg.getUrl());

            entity.put("noticeList", noticeInfoList);
            entity.put("hotkeyList", hotKeyList);
            entity.put("bannerList", bannerInfoList);
            entity.put("salePointList", salePointList);
            entity.put("recommendImg", recommendImgMap);
            entity.put("homeRecommend", homeRecommendMap);
            entity.put("specialList", appSpecialInfoList);
            entity.put("saleUserRecommend", saleUserRecommendDto);

            //缓存数据
//            HomeCacheManager.loadData(redisKey, entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            executorService.shutdown();
        }
        return RespUtil.success(entity);
    }

    private List<Map> getCategoryList() {
        List<Map> categoryList = new ArrayList<>();
        List<LitemallCategory> catL1List = categoryService.queryL1WithoutRecommend(0, SystemConfig.getCatlogListLimit());
        for (LitemallCategory catL1 : catL1List) {
            List<LitemallCategory> catL2List = categoryService.queryByPid(catL1.getId());
            List<Integer> l2List = new ArrayList<>();
            for (LitemallCategory catL2 : catL2List) {
                l2List.add(catL2.getId());
            }

            List<LitemallGoods> categoryGoods;
            if (l2List.size() == 0) {
                categoryGoods = new ArrayList<>();
            } else {
                categoryGoods = goodsService.queryByCategory(l2List, 0, SystemConfig.getCatlogMoreLimit());
            }

            Map<String, Object> catGoods = new HashMap<>();
            catGoods.put("id", catL1.getId());
            catGoods.put("name", catL1.getName());
            catGoods.put("goodsList", categoryGoods);
            categoryList.add(catGoods);
        }
        return categoryList;
    }


    @Transactional
    public BaseResult getHospitalLinkData(HospitalLinkDataVo hospitalLinkDataVo){
        AgedmallHospitalChannelLinkExample channelLinkExample=new AgedmallHospitalChannelLinkExample();
        channelLinkExample.createCriteria().andLinkUrlEqualTo(hospitalLinkDataVo.getCode());
        AgedmallHospitalChannelLink hospitalChannelLink = agedmallHospitalChannelLinkMapper.selectOneByExample(channelLinkExample);
        if(ObjectUtil.isNull(hospitalChannelLink)){
            return RespUtil.fail(500,"推广码不存在");
        }
        List<Integer> hospitalSendIdList=new ArrayList<>();
        String[] split = hospitalChannelLink.getHospitalIds().split(",");
        for (int i = 0; i < split.length; i++) {
            hospitalSendIdList.add(Integer.parseInt(split[i]));
        }
        AgedmallHospitalSendExample sendExample=new AgedmallHospitalSendExample();
        sendExample.createCriteria().andIdIn(hospitalSendIdList);
        List<AgedmallHospitalSend> agedmallHospitalSend = agedmallHospitalSendMapper.selectByExample(sendExample);
        HospitalLinkDataDto hospitalLinkDataDto=new HospitalLinkDataDto(hospitalChannelLink);
        //默认医院
        if(!agedmallHospitalSend.isEmpty()){
            hospitalLinkDataDto.setDefHosId(agedmallHospitalSend.get(0).getId());
        }
        List<HospitalSendData> hospitalList=new ArrayList<>();
        for (int i = 0; i < agedmallHospitalSend.size(); i++) {
            HospitalSendData hospitalSendData=new HospitalSendData(agedmallHospitalSend.get(i));
            hospitalList.add(hospitalSendData);
        }
        hospitalLinkDataDto.setHospitalList(hospitalList);
        //如果是护工，返回护工userId
        if(hospitalChannelLink.getGoodsShow()==1){
            AgedmallAgent agedmallAgent = agedmallAgentMapper.selectByPrimaryKey(hospitalChannelLink.getCarerId());
            if(agedmallAgent != null)
               hospitalLinkDataDto.setSaleUserId(agedmallAgent.getUserId());
        }
        return RespUtil.success(hospitalLinkDataDto);
    }


    /**
     * 添加推广记录
     * @param saleUserId
     */
    private void insertPromoteInformation(Integer saleUserId,Integer userId,AgedmallAgent agedmallAgent){
     AgedmallPromoteCount agedmallPromoteCount = new AgedmallPromoteCount();
     //推广人id
     agedmallPromoteCount.setPromoteUserId(saleUserId);
     if(userId != null){
         agedmallPromoteCount.setVisitUserId(userId);
     }else{
         agedmallPromoteCount.setVisitUserId(0);//表示不是注册用户
     }
     //根据推广人id查询推广方案
     //AgedmallAgent agedmallAgent = agedmallAgentMapper.selectByPrimaryKey(saleUserId);
     if(agedmallAgent != null){
         if(agedmallAgent.getPromotionScheme()!=null){
             agedmallPromoteCount.setPlanId(agedmallAgent.getPromotionScheme().intValue());
         }
         if(agedmallAgent.getShopId() != null){
             agedmallPromoteCount.setShopId(agedmallAgent.getShopId().toString());
         }

     }
     agedmallPromoteCount.setAddTime(LocalDateTime.now());
     //访问ip地址
      agedmallPromoteCount.setUserIp(IpUtil.getReqUserIp());

      agedmallPromoteCountMapper.insert(agedmallPromoteCount);
    }


    public  String getIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (!checkIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    private  boolean checkIP(String ip) {
        if (ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip)
                || ip.split(".").length != 4) {
            return false;
        }
        return true;
    }


    /**
     * 获取ip地址
     * @param request
     * @return
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }




}
